package com.wuge.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.wuge.common.to.SkuHasStockVo;
import com.wuge.common.to.SkuRedectionTo;
import com.wuge.common.to.SpuBrandTo;
import com.wuge.common.to.es.SkuEsModel;
import com.wuge.common.utils.R;
import com.wuge.gulimall.product.entity.*;
import com.wuge.gulimall.product.feign.CouponFeignService;
import com.wuge.gulimall.product.feign.ElasticSearchFeignService;
import com.wuge.gulimall.product.feign.WareFeignService;
import com.wuge.gulimall.product.service.*;
import com.wuge.gulimall.product.vo.*;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuge.common.utils.PageUtils;
import com.wuge.common.utils.Query;

import com.wuge.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CouponFeignService couponFeignService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private BrandService brandService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private ElasticSearchFeignService elasticSearchFeignService;
    @Override
    public void savaSpu(SpuSaveVo spuSaveVo) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setCreateTime(new Date());
        this.save(spuInfoEntity);
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveList(spuInfoEntity.getId(), images);
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map((attr) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            AttrEntity byId = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(byId.getAttrName());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);
        //调用优惠券系统
        SpuBrandTo spuBrandTo = new SpuBrandTo();
        Bounds bounds = spuSaveVo.getBounds();
        BeanUtils.copyProperties(bounds, spuBrandTo);
        spuBrandTo.setSpuId(spuInfoEntity.getId());
        couponFeignService.save(spuBrandTo);

        List<Skus> skus = spuSaveVo.getSkus();
        skus.stream().forEach((sku) -> {
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);

            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            String DefaultImage = null;
            for (Images image : sku.getImages()) {
                if (image.getDefaultImg() == 1) {
                    DefaultImage = image.getImgUrl();
                }
            }
            skuInfoEntity.setSkuDefaultImg(DefaultImage);
            skuInfoService.save(skuInfoEntity);
            Long skuId = skuInfoEntity.getSkuId();
            List<Images> images1 = sku.getImages();
            List<SkuImagesEntity> imagesEntities = images1.stream().filter((entity) -> {
                return !StringUtils.isEmpty(entity.getImgUrl());
            }).map((entity) -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setDefaultImg(entity.getDefaultImg());
                skuImagesEntity.setImgUrl(entity.getImgUrl());
                skuImagesEntity.setSkuId(skuId);
                return skuImagesEntity;
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(imagesEntities);
            List<Attr> attrs = sku.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrs.stream().map((attr) -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                skuSaleAttrValueEntity.setAttrName(attr.getAttrName());
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);
            SkuRedectionTo skuRedectionTo = new SkuRedectionTo();
            BeanUtils.copyProperties(sku, skuRedectionTo);
            skuRedectionTo.setSkuId(skuId);
            if (skuRedectionTo.getFullCount() > 0 || skuRedectionTo.getFullPrice().compareTo(BigDecimal.ZERO) == 1) {
                couponFeignService.saveSkuRelaction(skuRedectionTo);
            }


        });
//        以下为远程调用别的微服务对数据库的操作

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.like("spu_name", key);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)) {
            if (!"0".equals(catelogId)) {
                wrapper.eq("catalog_id", catelogId);
            }
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)) {
            if (!"0".equals(brandId)) {
                wrapper.eq("brand_id", brandId);
            }
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", brandId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void upSku(Long spuId) {
//        找到与spu关联的sku
        List<SkuInfoEntity> bySpuId = skuInfoService.findBySpuId(spuId);
//        获取与之关联的属性
        List<ProductAttrValueEntity> baseList = productAttrValueService.getBaseList(spuId);
        List<Long> idList = baseList.stream().map(entity -> {
            return entity.getAttrId();
        }).collect(Collectors.toList());
        // 获取可作为检索条件的属性
        List<Long> ids = attrService.getSearchAttrBySpuId(idList);
        Set<Long> set = new HashSet(ids);
        List<ProductAttrValueEntity> pattrs = baseList.stream().filter(baseAttr -> {
            return set.contains(baseAttr.getAttrId());
        }).collect(Collectors.toList());
        List<SkuEsModel.Attrs> attrs = pattrs.stream().map((pattr) -> {
            SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(pattr, attr);
            return attr;
        }).collect(Collectors.toList());
        /*通过远程调用获取商品是否有库存*/
        List<Long> list = bySpuId.stream().map(sku -> {
            return sku.getSkuId();
        }).collect(Collectors.toList());
        R hasStock = wareFeignService.getHasStock(list);
        TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {

        };
        List<SkuHasStockVo> hasStockData = hasStock.getData(typeReference);
        Map<Long, Boolean> map = hasStockData.stream().collect(Collectors.toMap(vo -> {
                    return vo.getSkuId();
                }, vo -> {
                    return vo.getHasStock();
                })
        );
        List<SkuEsModel> esModelList = bySpuId.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            if (map == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(map.get(sku.getSkuId()));
            }
            /*设置属性*/
            skuEsModel.setAttrs(attrs);
            //TODO 2、热度评分。0
            skuEsModel.setHotScore(0L);
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandId(brandEntity.getBrandId());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogId(categoryEntity.getCatId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            return skuEsModel;

        }).collect(Collectors.toList());
        R r = elasticSearchFeignService.saveSku(esModelList);
          if (r.getCode()==0){

              this.baseMapper.updateStatus(spuId);
          }
    }

    @Override
    public SpuInfoEntity getSpuBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);


        return getById(byId.getSpuId());
    }
}